package com.tianbing.adlottery.controller.storeadmin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.jubao.ejb.business.StoreBusiness;
import com.jubao.ejb.business.util.BusinessConstant;
import com.jubao.ejb.dao.CategoryDao;
import com.jubao.ejb.dao.StoreDao;
import com.jubao.ejb.entity.Category;
import com.jubao.ejb.entity.Store;
import com.tianbing.adlottery.helper.SkinUtils;
import com.tianbing.adlottery.util.ControllerFormBean;
import com.tianbing.adlottery.util.UserSession;

public class UpdateStorePrimaryCategoryController extends SimpleFormController {
	static Logger logger = Logger.getLogger(UpdateStorePrimaryCategoryController.class.getName());

	private CategoryDao categoryDao;

	private SkinUtils skinUtils;

	private StoreDao storeDao;
	private StoreBusiness storeBusiness;


	// ------------------GET Request LifeCycle------------------
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		ControllerFormBean fb = new ControllerFormBean();
		return fb;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      org.springframework.validation.BindException)
	 */
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object cmd,
			BindException ex) throws Exception {
		long childCatCounts = 0;
		ModelAndView mv = new ModelAndView(this.getSuccessView());

		UserSession auth = (UserSession) skinUtils.getUserAuthorization(request, response, true);
		Store store = storeDao.find(auth.getManagedStoreSysId());
		String type = ServletRequestUtils.getStringParameter(request, "type", "");
		String catid = ServletRequestUtils.getStringParameter(request, "catid", "");
		Category cat = categoryDao.find(catid);
		if (cat != null) {
			childCatCounts = categoryDao.getChildCategoryCount(cat.getSysId());
			if (childCatCounts == 0) {//only the category is leaf node
				if (type.equals("area")) {
					Category oldCat = store.getPrimaryAreaCategory();
					if (oldCat != null) {
						storeBusiness.removeFromCategoryTrail(store.getSysId(), oldCat.getSysId());
					}
					store.setPrimaryAreaCategory(cat);
					storeDao.save(store);
					storeBusiness.add2CateogryTrail(store.getSysId(), cat.getSysId());
				} else if (type.equals("business")) {
					Category oldCat = store.getPrimaryBusinessCategory();
					if (oldCat != null) {
						storeBusiness.removeFromCategoryTrail(store.getSysId(), oldCat.getSysId());
					}
					store.setPrimaryBusinessCategory(cat);
					storeDao.save(store);
					storeBusiness.add2CateogryTrail(store.getSysId(), cat.getSysId());
				}
			}
		}

		return mv;
	}

	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map model = new HashMap();
		String catid = ServletRequestUtils.getStringParameter(request, "catid", "");
		String type = ServletRequestUtils.getStringParameter(request, "type", "area");
		model.put("type",type);
		if (type.equals("area") && catid == "") {
			catid = BusinessConstant.CategoryID.AREA_CATEGORY_TOP.getId();
		} else if (type.equals("business") && catid == "") {
			catid = BusinessConstant.CategoryID.BUSINESS_CATEGORY_TOP.getId();
		}

		if (!catid.equals("")) {
			Category cat = categoryDao.find(catid);
			
			if (cat != null) {
				model.put("category", cat);
				List primaryCategoryTrail = categoryDao.getPrimaryCategoryTrail(cat.getSysId());
				List<Category> childCategoryList = categoryDao.getChildCategoryList(cat.getSysId(), 0, 100, null);
				model.put("primaryCategoryTrail", primaryCategoryTrail);
				model.put("childCategoryList", childCategoryList);
			}
		}

		UserSession auth = skinUtils.getUserAuthorization(request, null);
		Store store = storeDao.find(auth.getManagedStoreSysId());

		Category areaCat = store.getPrimaryAreaCategory();
		if (areaCat != null) {
			List<Category> storePrimaryAreaCategoryTrail = categoryDao.getPrimaryCategoryTrail(areaCat.getSysId());
			model.put("storePrimaryAreaCategoryTrail", storePrimaryAreaCategoryTrail);
		}

		Category businessCat = store.getPrimaryBusinessCategory();
		if (businessCat != null) {
			List<Category> storePrimaryBusinessCategoryTrail = categoryDao.getPrimaryCategoryTrail(businessCat
					.getSysId());
			model.put("storePrimaryBusinessCategoryTrail", storePrimaryBusinessCategoryTrail);
		}

		return model;
	}

	/**
	 * @param logger the logger to set
	 */
	public static void setLogger(Logger logger) {
		UpdateStorePrimaryCategoryController.logger = logger;
	}

	/**
	 * @param categoryDao the categoryDao to set
	 */
	public void setCategoryDao(CategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

	/**
	 * @param skinUtils the skinUtils to set
	 */
	public void setSkinUtils(SkinUtils skinUtils) {
		this.skinUtils = skinUtils;
	}

	/**
	 * @param storeDao the storeDao to set
	 */
	public void setStoreDao(StoreDao storeDao) {
		this.storeDao = storeDao;
	}

	/**
	 * @param storeBusiness the storeBusiness to set
	 */
	public void setStoreBusiness(StoreBusiness storeBusiness) {
		this.storeBusiness = storeBusiness;
	}
}
